package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.BaseException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void addDish(DishDTO dishDTO) {
        Dish dish=new Dish();
        //将前端传来的dto转换为对应数据库的实体
        BeanUtils.copyProperties(dishDTO,dish);
        if (dish.getStatus()==null){
            //设置新添加的菜品默认为禁用状态
            dish.setStatus(StatusConstant.DISABLE);
        }

        //将菜品增加到菜品表
        dishMapper.insert(dish);

        //查询该菜品的id
        Long dishId=dishMapper.selectByName(dish.getName());

        List<DishFlavor>dishFlavorList=new ArrayList<>();
        for (int i = 0; i < dishDTO.getFlavors().size(); i++) {
            DishFlavor curDTO=dishDTO.getFlavors().get(i);
            DishFlavor dishFlavor=new DishFlavor();
            dishFlavor.setDishId(curDTO.getDishId());
            dishFlavor.setId(curDTO.getId());
            dishFlavor.setName(curDTO.getName());
            dishFlavor.setValue(curDTO.getValue());
            dishFlavor.setDishId(dishId);
            dishFlavorList.add(dishFlavor);
        }

        //将口味进行批量插入
        dishFlavorMapper.insertBatch(dishFlavorList);

        //清理缓存
        clearRedis();
    }

    @Override
    public PageResult selectPage(DishPageQueryDTO dishPageQueryDTO) {
        //开启分页
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

        //执行条件查询
        Page<DishVO> page =dishMapper.selectPage(dishPageQueryDTO);


        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public void deleteBatch(List<Long> ids) {
        //1.判断是否有菜品处于起售状态
        if (dishMapper.countEnableStatus(ids)>0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }


        //2.判断菜品是否关联了套餐
        if (setmealMapper.selectAboutSetmealByDishIds(ids).size()>0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }


        //3.根据id删除菜品,并删除对应的口味
        dishMapper.deleteBatch(ids);
        dishFlavorMapper.deleteBatchByDishIds(ids);

        //清理缓存
        clearRedis();
    }

    @Override
    public DishVO selectById(Long id) {
        //根据id查询菜品
        Dish dish=dishMapper.selectById(id);

        //根据菜品id查询菜品的口味
        List<DishFlavor>dishFlavorList=dishFlavorMapper.selectByDishId(id);

        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavorList);
        return dishVO;
    }

    @Override
    public List<Dish> selectByCategoryId(Long categoryId) {
        return dishMapper.selectByCategoryId(categoryId);
    }

    @Override
    public void updateDish(DishDTO dishDTO) {
        //删除该菜品相关的所有口味
        dishFlavorMapper.deleteByDishId(dishDTO.getId());

        if (dishDTO.getFlavors()!=null&&dishDTO.getFlavors().size()>0){
            //添加新设置的口味
            for (int i = 0; i < dishDTO.getFlavors().size(); i++) {
                dishDTO.getFlavors().get(i).setDishId(dishDTO.getId());
            }
            dishFlavorMapper.insertBatch(dishDTO.getFlavors());
        }

        Dish dish=new Dish();
        BeanUtils.copyProperties(dishDTO,dish);

        //更新菜品信息
        dishMapper.update(dish);

        //清理缓存
        clearRedis();
    }

    @Override
    public void setStartOrStop(Long id, Integer status) {
        //判断该菜品有没有关联的套餐
        if (setmealMapper.selectAboutSetmealByDishId(id).size()>0){
            throw new BaseException("菜品"+id+"有关联的套餐");
        }

        dishMapper.setStatus(id,status);

        //清理缓存
        clearRedis();
    }

    @Override
    public List<DishVO> selectDishVoListConditionBy(Long categoryId, Integer enable) {
        //先从redis中查询有没有缓存的数据，如果有则直接使用缓存
        List<DishVO>dishVOList= (List<DishVO>) redisTemplate.opsForValue().get("category_"+categoryId);
        if (dishVOList!=null&&dishVOList.size()>0){
            return dishVOList;
        }

        dishVOList=new ArrayList<>();
        //查询出所有满足条件的dish
        List<Dish>dishList=dishMapper.selectDishConditionBy(categoryId,enable);
        //拷贝属性，顺便查询出每个dish对应分类的名字，口味
        for (Dish dish : dishList) {
            DishVO dishVO=new DishVO();
            BeanUtils.copyProperties(dish,dishVO);
            dishVO.setFlavors(dishFlavorMapper.selectByDishId(dish.getId()));
            dishVO.setCategoryName(categoryMapper.selectNameById(dish.getId()));
            dishVOList.add(dishVO);
        }

        //没有缓存，则将数据存到缓存去
        redisTemplate.opsForValue().set("category_"+categoryId,dishList);

        return dishVOList;
    }


    private void clearRedis(){
        Set keys = redisTemplate.keys("*");
        redisTemplate.delete(keys);
    }

}
